package com.zy.pro.letter.web;

import java.io.PrintWriter;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.core.model.PageView;
import com.zy.core.web.BaseController;
import com.zy.pro.letter.model.Letter;
import com.zy.pro.letter.service.LetterService;
import com.zy.pro.letter.web.form.LetterSearchForm;
import com.zy.pro.order.model.OrderItem;
import com.zy.pro.order.service.OrderItemService;
import com.zy.pro.shop.model.Shop;
import com.zy.pro.shop.service.ShopService;
import com.zy.pro.system.web.form.GlobalForm;
import com.zy.pro.system.web.form.MenuForm;
import com.zy.pro.user.model.User;
import com.zy.pro.user.service.UserService;
import com.zy.utils.MethodUtil;
import com.zy.utils.SessionUtils;
import com.zy.utils.UUIDHelper;
/**
 * 站内信管理控制器
 *
 */
@Controller
@RequestMapping("/control/letter/letterController")
public class LetterController extends BaseController {

	private static final Logger logger = Logger.getLogger(LetterController.class);
	
	/**
	 * 站内信管理服务类
	 */
	@Resource(name = "letterServiceImpl")
	private LetterService letterService;
	
	/**
	 * 店铺管理服务类
	 */
	@Resource(name = "shopServiceImpl")
	private ShopService shopService;
	
	/**
	 * 系统管理员管理服务类
	 */
	@Resource(name = "userServiceImpl")
	private UserService userService;
	
	/**
	 * 订单管理服务类
	 */
	@Resource(name = "orderItemServiceImpl")
	private OrderItemService orderItemService;
	
	/**
	 * 用户对店铺发送站内信
	 * @param letter
	 * @param map
	 * @return
	 */
	@RequestMapping("/userAddLetter")
	@ResponseBody	//返回json类型对象,需要添加响应body的注释
	public JSON userAddLetter(Letter letter, ModelMap map) {
		JSONObject obj = new JSONObject();
		obj.put("status", "");//状态
		obj.put("info", "");//返回内容
		try {
			//设置站内信创建时间
			letter.setLetterCreateTime(new Date());
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			letter.setLetterType(1);
			//设置站内信类型状态(1:普通,2:确认金额执行,3:付款,4:退款,5:删除)
			letter.setLetterTypeStatus(1);
			//设置站内信状态(1:正常,2:冻结,3:删除)
			letter.setLetterStatus(1);
			//设置站内信店铺阅读状态(0:发送1:未读,2:已读)
			letter.setLetterShopStatus(1);
			//设置站内信用户阅读状态(0:发送1:未读,2:已读)
			letter.setLetterUserStatus(0);
			//设置站内信主键
			letter.setLetterId(UUIDHelper.getUUID36());
			
			//保存站内信
			letterService.save(letter);
			
			obj.put("status", "y");
			obj.put("info", letter.getLetterId());
			
			return obj;
		} catch (Exception e) {
			logger.error(e);
			return obj;
		}
	}
	
	
	/**
	 * 用户中心/店铺中心 查看站内信详情
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/displayLetterDetail")
	public String displayLetterDetail(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			User user = SessionUtils.getUser(request);
			if(user != null){
				MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_LETTER,0);
				map.addAttribute("menuForm", menuForm);
			}else{
				MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_LETTER,0);
				map.addAttribute("menuForm", menuForm);
			}
			
			Letter letter = letterService.find(form.getLetterId());
			//判断发送状态,阅读主键,阅读状态,修改阅读者的阅读状态
			if(letter.getLetterType() == 1 && form.getLetterShopId() != null && letter.getLetterShopStatus() == 1){
				//判断如果是用户发送的站内信,且由点卖家查看时,并且,卖家查看之前的状态是未读,则修改卖家对次站内信的阅读状态(0:发送1:未读,2:已读)
				letter.setLetterShopStatus(2);
				Letter leInfo = new Letter();
				leInfo.setLetterId(form.getLetterId());
				leInfo.setLetterShopStatus(2);
				letterService.updateBySelective(leInfo);
				map.addAttribute("reqUrl", "control/letter/letterController/shopUnreadLetterList.do?letterShopId="+form.getLetterShopId());
			}else if(letter.getLetterType() == 2 && form.getLetterUserId() != null && letter.getLetterUserStatus() == 1){
				//判断如果是店铺卖家发送的站内信,且由点用户查看时,并且,用户查看之前的状态是未读,则修改用户对次站内信的阅读状态(0:发送1:未读,2:已读)
				letter.setLetterUserStatus(2);
				Letter leInfo = new Letter();
				leInfo.setLetterId(form.getLetterId());
				leInfo.setLetterUserStatus(2);
				letterService.updateBySelective(leInfo);
				//返回路径
				map.addAttribute("reqUrl", "control/letter/letterController/userUnreadLetterList.do?letterUserId="+form.getLetterUserId());
			}
			map.addAttribute("letter", letter);
			map.addAttribute("form", form);
			
			return "control/jsp/letter_detail";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 用户中心/店铺中心 查看站内信详情后跳转回复页
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/displayReplyLetter")
	public String displayReplyLetter(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			User u = SessionUtils.getUser(request);
			if(u != null){
				MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_LETTER,0);
				map.addAttribute("menuForm", menuForm);
			}else{
				MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_LETTER,0);
				map.addAttribute("menuForm", menuForm);
			}
			
			if(form.getLetterShopId() != null){
				Shop shop = shopService.find(form.getLetterShopId());
				map.addAttribute("shop", shop);
			}else if(form.getLetterUserId() != null){
				User user = userService.find(form.getLetterUserId());
				map.addAttribute("user", user);
			}
			Letter letter = letterService.find(form.getLetterId());
			map.addAttribute("letter", letter);
			map.addAttribute("form", form);
			
			return "control/jsp/letter_reply";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 站内信回复功能(用户回复/店铺回复)
	 * @param letter
	 * @param map
	 * @return
	 */
	@RequestMapping("/replyLetter")
	@ResponseBody	//返回json类型对象,需要添加响应body的注释
	public JSON replyLetter(Letter letter, ModelMap map) {
		JSONObject obj = new JSONObject();
		obj.put("status", "");//状态
		obj.put("info", "");//返回内容
		try {
			//设置站内信创建时间
			letter.setLetterCreateTime(new Date());
			//设置站内信状态(1:正常,2:冻结,3:删除)
			letter.setLetterStatus(1);
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			//letter.setLetterType(1);
			//设置站内信类型状态(1:普通,2:确认金额执行,3:付款,4:退款,5:删除)
			letter.setLetterTypeStatus(1);
			//根据站内信回复时发送的类型设置用户/店铺站内信的状态
			if(letter.getLetterType() != null && letter.getLetterType() == 1){
				//设置站内信店铺阅读状态(0:发送1:未读,2:已读)
				letter.setLetterShopStatus(1);
				//设置站内信用户阅读状态(0:发送1:未读,2:已读)
				letter.setLetterUserStatus(0);
			}else if(letter.getLetterType() != null && letter.getLetterType() == 2){
				//设置站内信店铺阅读状态(0:发送1:未读,2:已读)
				letter.setLetterShopStatus(0);
				//设置站内信用户阅读状态(0:发送1:未读,2:已读)
				letter.setLetterUserStatus(1);
			}
			//设置站内信主键
			letter.setLetterId(UUIDHelper.getUUID36());
			//根据站内信的父主键,判断是否站内信存在最初始主键,如果存在,设置最初始主键
			if(letter.getLetterPrvId() != null && !"".equals(letter.getLetterPrvId())){
				Letter prvLetter = letterService.find(letter.getLetterPrvId());
				if(prvLetter != null){
					if(prvLetter.getPrvId() != null && !"".equals(prvLetter.getPrvId())){
						//设置最初始主键
						letter.setPrvId(prvLetter.getPrvId());
					}else if(prvLetter.getPrvId() == null || "".equals(prvLetter.getPrvId())){
						if(prvLetter.getLetterPrvId() != null && !"".equals(prvLetter.getLetterPrvId())){
							//设置最初始主键
							letter.setPrvId(prvLetter.getLetterPrvId());
						}else {
							//设置最初始主键
							letter.setPrvId(letter.getLetterPrvId());
						}
					}
				}else{
					//如果站内信的父类主键查询不到信息,把父类主键设置为空
					letter.setLetterPrvId(null);
				}
			}
			//保存订单
			letterService.save(letter);
			
			obj.put("status", "y");
			obj.put("info", letter.getLetterId());
			
			return obj;
		} catch (Exception e) {
			logger.error(e);
			return obj;
		}
	}
	
	
	/**
	 * 用户中心 - 用户已发送站内信列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/userSentLetterList")
	public String userSentLetterList(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_LETTER,MenuForm.SUB_TYPE_USER_LETTER_SENT);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("letterCreateTime", "desc");
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			form.setLetterType(1);
			//设置站内信状态(1:正常,2:冻结,3:删除)
			form.setLetterStatus(1);
			//创建页面对象
			PageView<Letter> pageView = new PageView<Letter>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(letterService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/letter/letterController/userSentLetterList.do?letterUserId="+form.getLetterUserId());
			
			return "control/jsp/user/mess_y0";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 用户中心 - 用户未读站内信列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/userUnreadLetterList")
	public String userUnreadLetterList(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_LETTER,MenuForm.SUB_TYPE_USER_LETTER_UNREAD);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("letterCreateTime", "desc");
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			form.setLetterType(2);
			//设置站内信状态(1:正常,2:冻结,3:删除)
			form.setLetterStatus(1);
			//设置站内信用户阅读状态(0:发送1:未读,2:已读)
			form.setLetterUserStatus(1);
			//创建页面对象
			PageView<Letter> pageView = new PageView<Letter>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(letterService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/letter/letterController/userUnreadLetterList.do?letterUserId="+form.getLetterUserId());
			
			return "control/jsp/user/mess_y1";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 用户中心 - 用户已读站内信列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/userReadLetterList")
	public String userReadLetterList(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_LETTER,MenuForm.SUB_TYPE_USER_LETTER_READ);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("letterCreateTime", "desc");
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			form.setLetterType(2);
			//设置站内信状态(1:正常,2:冻结,3:删除)
			form.setLetterStatus(1);
			//设置站内信用户阅读状态(0:发送1:未读,2:已读)
			form.setLetterUserStatus(2);
			//创建页面对象
			PageView<Letter> pageView = new PageView<Letter>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(letterService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/letter/letterController/userReadLetterList.do?letterUserId="+form.getLetterUserId());
			
			return "control/jsp/user/mess_y2";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 卖家中心 - 站内信发送列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/shopSentLetterList")
	public String shopSentLetterList(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_LETTER,MenuForm.SUB_TYPE_SELLER_LETTER_SENT);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("letterCreateTime", "desc");
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			form.setLetterType(2);
			//设置站内信状态(1:正常,2:冻结,3:删除)
			form.setLetterStatus(1);
			//创建页面对象
			PageView<Letter> pageView = new PageView<Letter>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(letterService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/letter/letterController/shopSentLetterList.do?letterShopId="+form.getLetterShopId());
			
			return "control/jsp/seller/letter_0";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 卖家中心 - 站内信未读列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/shopUnreadLetterList")
	public String shopUnreadLetterList(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_LETTER,MenuForm.SUB_TYPE_SELLER_LETTER_UNREAD);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("letterCreateTime", "desc");
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			form.setLetterType(1);
			//设置站内信状态(1:正常,2:冻结,3:删除)
			form.setLetterStatus(1);
			//设置站内信店铺阅读状态(0:发送1:未读,2:已读)
			form.setLetterShopStatus(1);
			//创建页面对象
			PageView<Letter> pageView = new PageView<Letter>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(letterService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/letter/letterController/shopUnreadLetterList.do?letterShopId="+form.getLetterShopId());
			
			return "control/jsp/seller/letter_w";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 卖家中心 - 站内信已读列表
	 * @param form
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/shopReadLetterList")
	public String shopReadLetterList(LetterSearchForm form,ModelMap map,HttpServletRequest request){
		try {
			
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_SELLER,MenuForm.PAR_TYPE_SELLER_LETTER,MenuForm.SUB_TYPE_SELLER_LETTER_READ);
			map.addAttribute("menuForm", menuForm);
			
			form.getOrderby().put("letterCreateTime", "desc");
			//设置站内信类型(1:用户发送,店家接收,2:店家发送,用户接收)
			form.setLetterType(1);
			//设置站内信状态(1:正常,2:冻结,3:删除)
			form.setLetterStatus(1);
			//设置站内信店铺阅读状态(0:发送1:未读,2:已读)
			form.setLetterShopStatus(2);
			//创建页面对象
			PageView<Letter> pageView = new PageView<Letter>(3, form.getPage());
			form.setFirstResult(pageView.getFirstResult());
			form.setMaxResult(pageView.getMaxresult());
			pageView.setQueryResult(letterService.getData(form));
			map.addAttribute("pageView", pageView);
			map.addAttribute("form", form);
			map.addAttribute("reqUrl", "/control/letter/letterController/shopReadLetterList.do?letterShopId="+form.getLetterShopId());
			
			return "control/jsp/seller/letter_y";
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 *	验证站内信关联订单是否存在,是否是用户与店铺之间的订单
	 * @param form
	 */
	@RequestMapping("/checkOrderByUserAndShop")
	@ResponseBody
	public JSON checkOrderByUserAndShop(GlobalForm form, HttpServletRequest request){
		JSONObject json = new JSONObject();
		json.put("status", "n");
		json.put("info", "Order number does not exist!");
		try {
			//param代表订单号
			//letterUserId代表参与订单的用户主键
			//letterShopId代表参与订单的店铺主键
			if(form.getParam() != null && !"".equals(form.getParam())){
				OrderItem order = orderItemService.find(form.getParam());
				if(order != null && order.getOrderStatus() != 3){
					if(order.getOrderUserId() == form.getLetterUserId() && order.getOrderShopId() == form.getLetterShopId()){
						json.put("status", "y");
						json.put("info", "Through verification!");
						logger.info("站内信发送/回复-验证订单号是否是用户与店铺之间的订单,验证通过！");
					}else{
						json.put("info", "The order is not between you and your partner!");
						logger.info("站内信发送/回复-验证订单号是否是用户与店铺之间的订单,验证结果为不是,验证失败！");
					}
				}else{
					logger.info("站内信发送/回复-验证订单号是否是用户与店铺之间的订单,订单不存在,验证失败！");
				}
			}else{
				logger.info("站内信发送/回复-验证订单号是否是用户与店铺之间的订单,订单号不能为空,验证失败！");
			}
		} catch (Exception e) {
			logger.error("站内信发送/回复-验证订单号是否是用户与店铺之间的订单验证失败，输入错误！",e);
		}
		return json;
	}
}
